<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElTree, ElMessageBox } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import { useRoute } from 'vue-router'
import TreeUtilDTO from '@/utils/tree'
import TreeUtil from '@/utils/tree'
import wjzs from '@/components/wjzs.vue'
import printFn from '@/utils/print'
const route = useRoute()
const wjzsRef = ref<InstanceType<typeof wjzs>>()

const emit = defineEmits(['refresh'])
// 入参
const form = ref({
  gjz: '',
})

// 生命周期
onMounted(() => {
  // 查询纸质目录
  queryZzml()
})

const defaultProps = {
  children: 'children',
  label: 'mc',
  disabled: (data: any) => {
    if (data.cj === '1' && data.sfzzaj !== 'Y') return true
    else if ((data.cj === '2' && data.sfzzajml !== 'Y') || data.sfzzajmls === 'N') return true
    return false
  },
}

/*
 * 查询纸质目录
 */
const queryZzml = () => {
  //
}
const treeRef = ref<InstanceType<typeof ElTree>>()

// 文字过滤
const filtersTree = () => {
  treeRef.value?.filter(form.value.gjz)
}

const zzmlTreeData = ref<any[]>([])
const queryAjml = async () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: '0',
  }
  wsjzglService
    .queryAjmls(params)
    .then(async (res) => {
      const obj = route.query
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })

      let filteredData = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')

      filteredData.forEach((item: any) => {
        if (item.children && item.children.length > 0) {
          item.children = item.children.filter((el: any) => {
            if (el.mc !== '待编目材料') {
              return item
            }
          })
          item.children.forEach((data1: any) => {
            item.wjsl += Number(data1.wjsl)
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })
      zzmlTreeData.value = filteredData
      zzmlTreeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            if (data1.children && data1.children.length > 0) {
              // 目录都不是纸质目录，案卷也不能勾选
              if (data1.children.every((data2: any) => data2.sfzzajml !== 'Y')) {
                data1['sfzzaj'] = 'N'
              }
              data1.children.forEach((data2: any) => {
                if (data1.bh === data2.fbh && data1.mc === '正卷') {
                  data2['zfj'] = '正卷'
                }
                if (data1.bh === data2.fbh && data1.mc === '副卷') {
                  data2['zfj'] = '副卷'
                }
                // 案卷设置了无纸质案卷，所有目录都不能勾选
                if (data1.sfzzaj === 'N') {
                  data2['sfzzajmls'] = 'N'
                }
              })
            }
          })
        }
      })
      let newArr = TreeUtil.flatten(zzmlTreeData.value)
      const checkList = newArr
        .filter((item) => item.sfysczzml === 'Y' && item.cj !== '1')
        .map((el) => el.bh)

      if (checkList && checkList.length) {
        await nextTick(() => {
          treeRef.value?.setCheckedKeys(checkList)
        })
        getUrlTgspb()
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getUrlTgspb = () => {
  checkNodes.value = treeRef.value?.getCheckedNodes() as any
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    gdbh: route.query.gdbh as unknown as string,
  }
  zzmlParams.value = params
  zzmlUrl.value = '/api/wsjzgl/getZzml'
  wsjzglService
    .getZzml(params)
    .then((res: any) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        url.value = window.URL.createObjectURL(res.data)
        isShowSave.value = false
        isShowLoad.value = true
        yhtsShow.value = true
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 树节点点击
const treeNodeClick = () => {
  form.value.gjz = ''
}

/**
 * 树节点过滤
 */
const filtersNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

const yhtsShow = ref(false)

/*
 * 生成目录
 */
const url = ref()
const createZzml = () => {
  if (!checkNodes.value || checkNodes.value?.length <= 0)
    return ElMessage({ type: 'error', message: '请勾选目录' })
  if (yhtsShow.value) {
    ElMessageBox.confirm('目录已存在,是否重新生成？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      getScmlApi()
    })
    return
  }
  getScmlApi()
}
const zzmlParams = ref()
const zzmlUrl = ref('')
// 生成目录接口
const getScmlApi = () => {
  const temp: any = {}
  const list = checkNodes.value.filter((el: any) => el.cj === '2')
  list.forEach((el: any) => {
    if (temp[el.fbh]) {
      temp[el.fbh].push(el)
    } else {
      temp[el.fbh] = [el]
    }
  })
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    zzmlxxList: Object.keys(temp).map((key) => ({
      ajbh: temp[key][0].ajbh as string,
      mlbhList: temp[key].map((item: any) => item.bh) as string[],
      mllx: temp[key][0].zfj === '正卷' ? '1' : '2',
    })),
  }
  zzmlParams.value = params
  zzmlUrl.value = '/api/wsjzgl/createZzml'
  wsjzglService
    .createZzml(params, route.query.ajbh as string)
    .then((res: any) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        url.value = window.URL.createObjectURL(res.data)
        isShowSave.value = true
        isShowLoad.value = false
        yhtsShow.value = true
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 打开弹框
 */
const dialogVisible = ref(false)
const openDialog = () => {
  queryAjml()
  dialogVisible.value = true
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  url.value = null
  dialogVisible.value = false
  isShowSave.value = false
  isShowLoad.value = false
  yhtsShow.value = false
  emit('refresh')
}

/*
 * 保存（成功抛出刷新）
 */
const isShowSave = ref(false)
const isShowLoad = ref(false)
const loading = ref(false)
const save = () => {
  if (!checkNodes.value || checkNodes.value?.length <= 0)
    return ElMessage({ type: 'error', message: '请勾选目录' })
  const temp: any = {}
  const list = checkNodes.value.filter((el: any) => el.cj === '2')
  list.forEach((el: any) => {
    if (temp[el.fbh]) {
      temp[el.fbh].push(el)
    } else {
      temp[el.fbh] = [el]
    }
  })
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    zzmlxxList: Object.keys(temp).map((key) => ({
      ajbh: temp[key][0].ajbh as string,
      mlbhList: temp[key].map((item: any) => item.bh) as string[],
      mllx: temp[key][0].zfj === '正卷' ? '1' : '2',
    })),
  }
  zzmlParams.value = params
  zzmlUrl.value = '/api/wsjzgl/saveZzml'
  loading.value = true
  wsjzglService
    .saveZzml(params, route.query.ajbh as string)
    .then((res) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        ElMessage({ type: 'success', message: '保存成功' })
        url.value = window.URL.createObjectURL(res.data)
        isShowSave.value = false
        isShowLoad.value = true
        yhtsShow.value = true
        nextTick(() => {
          wjzsRef.value?.init()
        })
        emit('refresh')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const checkNodes = ref<any>([])
const checkChange = (data: any, checks: any) => {
  checkNodes.value = checks.checkedNodes
}

// 下载按钮
const download = () => {
  const downloadElement = document.createElement('a')
  downloadElement.href = url.value
  downloadElement.download = '纸质目录.pdf'
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
}

// 打印按钮
const printingClick = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '纸质目录.pdf',
    loadingHeader: {
      ajbh: route.query.ajbh,
    },
    loadingParam: zzmlParams.value,
    loadingUrl: `${window.IPCONFIG}${zzmlUrl.value}`,
    requestMethodName: 'POST',
  }
  printFn(params)
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="纸质目录"
    width="70%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="left-tree">
        <header class="dialog-header">
          <el-input
            v-model="form.gjz"
            autosize=""
            placeholder="请输入查询关键字"
            @change="filtersTree"
          >
            <template #suffix>
              <el-icon @click="filtersTree" class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </header>
        <div class="tree-box">
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="zzmlTreeData"
            show-checkbox
            node-key="bh"
            highlight-current
            default-expand-all
            :expand-on-click-node="false"
            :props="defaultProps"
            @node-click="treeNodeClick"
            @check="checkChange"
            :filter-node-method="filtersNode"
          >
            <template #default="{ data }">
              <div class="custom-tree-node">
                <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
                <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
                <img
                  v-if="data.mc === '正卷' || data.mc === '副卷'"
                  src="/src/assets/images/dbm.png"
                  alt=""
                />
                <img v-if="data.mc === '待编目材料'" src="/src/assets/images/juan.png" alt="" />
                <img
                  v-if="
                    data.cj === '2' && data.sfdzajml === 'Y' && (data.sfyy === 'N' || !data.sfyy)
                  "
                  style="margin-right: 5px"
                  src="/src/assets/images/xswjwyz.png"
                  alt=""
                />
                <img
                  v-if="data.cj === '2' && data.sfdzajml === 'Y' && data.sfyy === 'Y'"
                  style="margin-right: 5px"
                  src="/src/assets/images/xsxwjyyz.png"
                  alt=""
                />
                <img
                  v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
                  src="/src/assets/images/xxwj.png"
                  alt=""
                />
                <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mc"
                  >&nbsp;{{ data.mc }}&nbsp;</span
                >
                <span>({{ data.wjsl }})</span>
              </div>
            </template>
          </el-tree>
        </div>
        <div class="scml-button">
          <el-button type="success" @click="createZzml">生成目录</el-button>
          <div class="pageNumber">*勾选文件页数大于200将自动进行分册</div>
        </div>
      </div>
      <div class="right-edit">
        <wjzs ref="wjzsRef" v-if="url" wjlx="pdf" :url="url" />
        <div v-else><el-empty description="暂无数据" /></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-if="isShowLoad" @click="download">下载</el-button>
        <el-button type="primary" v-if="isShowLoad" @click="printingClick">打印</el-button>
        <el-button type="primary" v-if="isShowSave" @click="save" :loading="loading"
          >保存目录</el-button
        >
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  height: 70vh;
  display: flex;

  .left-tree {
    flex: 2;
    display: flex;
    flex-direction: column;
    .tree-box {
      flex: 1;
      flex-shrink: 0;
      overflow: auto;
    }

    .scml-button {
      display: flex;
      align-items: center;

      .pageNumber {
        margin-left: 10px;
        color: #e8a85f;
      }
    }
  }

  .right-edit {
    flex: 5;
    margin-left: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.el-input__icon {
  cursor: pointer;
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
